package jee.boot.common.utils;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 模板编辑工具
 */
public class MatcherCompilationHelper {
    private static Logger logger = LoggerFactory.getLogger(MatcherCompilationHelper.class);

    /**
     * 简单的编译,str中包含${param}/#{param},将str中的变量替换成object中的对应的数据
     *
     * @param object
     * @param str
     * @return
     */
    public static String simpleCompilation(Object object, String str) {
        String s = compilation1(object, str);
        String s1 = compilation2(object, s);
        return s1;
    }

    private static String compilation1(Object object, String str) {
        if (StringUtils.isBlank(str) || object == null) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        String pattern = "\\$\\{(.+?)\\}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(str);
        while (m.find()) {
            String key = m.group(1);
            Object value = null;
            try {
                value = PropertyUtils.getProperty(object, key);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    private static String compilation2(Object object, String str) {
        if (StringUtils.isBlank(str) || object == null) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        String pattern = "\\#\\{(.+?)\\}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(str);
        while (m.find()) {
            String key = m.group(1);
            Object value = null;
            try {
                value = PropertyUtils.getProperty(object, key);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            m.appendReplacement(sb, "'" + (value == null ? "" : value.toString()) + "'");
        }
        m.appendTail(sb);
        return sb.toString();
    }

}
